import MD5 from './md5'
import {deepMerge} from '../libs/object.js' 
var taskArr=[]
export default {
	Config: {
		debug:true,
		local:''
	},
	//对文件地址格式化
	FileFormat:function(_option,fileUrl=''){
		let option={
			type:'http',//文件是本地还是远程
			host:'',//匹配的域名
			url:fileUrl,//被匹配的地址
			mod:'',//匹配模式
			style:{ //

			}
		}
		option=deepMerge(option,_option)
		let {type,url,host,mod,style}=option
		//补全相对地址
		if(type=='http'){
			if(url.indexOf('http')==-1){
				url=host+url
			}
			//进入模式匹配
			if(url.indexOf(host) != -1){
				if(mod&&style[mod]){
					url=url+style[mod]
				}
			}
		}
		//url=url.replaceAll('//','/').replace(':','://')
		return url
	},
	DownloadFile:async function(option){
		let that=this
		let {path,type,newSp,postf,newName,newPath,filetype}=option
		return new Promise((resolve, reject)=>{
			//如果是本地文件则直接返回
			if(filetype=='local'){
				uni.getFileInfo({
					filePath:path,
					success(res) {
						resolve(path)
					},
					fail(e) {
						console.log(e)
						reject(path)
					}
				})
			}else{
				//#ifdef APP-PLUS
				var dtask = plus.downloader.createDownload(path, {
					filename:newPath,priority:-1
				}, function(d, status){
						// 下载完成
						if(status == 200){
							resolve(d.filename)
							//console.log("Download success: " + d.filename);
						} else {
							 reject(path)
						}
					});
					taskArr.push(dtask)
					that.startDownTask()
					//dtask.start();
				//#endif
				//#ifndef APP-PLUS
				uni.downloadFile({
					url:path,
					success:(res)=>{
						resolve(res.tempFilePath)
					},
					fail:(e)=>{
						reject(path)
					}
				})
					//#endif
			}
			//否则则下载
		})
	},
	startDownTask:function(){
		let that=this
		if(taskArr.length>0){
			console.log('taskCount--'+taskArr.length)
			var tk=taskArr.shift()
			var newArr=taskArr
			if(newArr.length>0){
				 setTimeout(that.startDownTask,300)
			}
			tk.start()
		}
	},
	FileCopyTo:async function(_option){
		let isDebug=this.Config.debug
		let option={
			source:'',//被复制的文件
			target :'',//复制后的路径
			dirBase:'_doc',//保存路径根目录
			dirSub:'',//保存路径子目录
		}
		option={...option,..._option}
		let {source,target,dirBase,dirSub}=option
		let newPath=dirBase+'/'+dirSub+'/'+target
		return new Promise((resolve, reject)=>{
			//#ifndef APP-PLUS
			reject(source)
			//#endif
			//#ifdef APP-PLUS
			plus.io.resolveLocalFileSystemURL(source,function(f){
				//console.log('打开f')
				//打开许保存的_DOC目录
				plus.io.resolveLocalFileSystemURL(dirBase,function(p1){
					//打开子目录
					//console.log('打开p1')
					p1.getDirectory(dirSub, {create:true,exclusive:false},function(p2){
						//console.log('打开p2')
						//复制文件
						f.copyTo(p2,target,function(entry){
							if(isDebug){
								console.log('copyTo cachePath--'+newPath)
							}
							resolve(newPath)
						},function(e){
							console.log(e)
							reject(source)
						})

					},function(e){
						console.log(e)
						reject(source)
					})
				},function(e){
					console.log(e)
					reject(source)
				})
			},function(e){
				console.log(e)
				reject(source)
			})
			//#endif
		}
		)
	},
	//批量缓存文件
	CacheFiles: function(option,files,callback=null){

		for(let i=0;i<files.length;i++){
			let path=files[i]
			option={...option,...{url:path}},
			this.CacheFile(option).then((res)=>{
				callback({index:i,result:res,state:true})
			})
		}
		callback({index:files.length,result:{},state:false})

		/*
		console.log('CacheFiles-----'+index)
		if(index<files.length){
			let path=files[index]
			option={...option,...{url:path}}
			let that=this
			this.CacheFile(option).then((res)=>{
				//console.log('---result---'+)
				if(callback!=null){
					callback({index:index,result:res,state:true})
				}

				that.CacheFiles(option,files,callback,index+1)
			}).catch((e)=>{
				if(callback!=null){
					callback({index:index,result:{},state:false})
				}
			})

		}else{
			if(callback!=null){
				callback({index:index,result:{},state:false})
			}
		}
		*/
	},
	GetFileInfo:async function(option){
		let {path}=option
		return new Promise((resolve, reject)=>{
			uni.getFileInfo({
				filePath:newPath,
				success(res) {
					resolve({ret:true,info:res})
				},
				fail() {
					resolve({ret:false,info:null})
				}
			})
		})
	},
	//缓存文件
	CacheFile:async function(option){
		let conf={
			id:'',//自定义本地编号
			type:'http',//local
			base64:false, //是否转base64
			url:'', //路径
			result:'cache',//path,down,cache 返回最终结果优先级
			group:true,//是否分组
			format:null,
			config:{}
		}
        let {callback}=option
		conf={...conf,...option}
		let cacheConf={...this.Config,...conf.config}
		let localTf=cacheConf.local

		if(conf.format){
			//console.log(conf.format)
			conf.url=this.FileFormat(conf.format,conf.url)
			//console.log(conf.url)
		}
		return new Promise((resolve, reject)=>{
			let path=conf.url
			if(conf.type=='local'){
				path=localTf+path
			}

			//#ifdef H5
            callback&&callback({cache:false,msg:'H5暂不支持文件缓存',type:'source',path:path})
			resolve({cache:false,msg:'H5暂不支持文件缓存',type:'source',path:path})
			return
			//#endif
			//#ifdef MP
            callback&&callback({cache:false,msg:'MP暂不支持文件缓存',type:'source',path:path})
			resolve({cache:false,msg:'MP暂不支持文件缓存',type:'source',path:path})
			return
			//#endif
			let postf='png'
			let sp0=path.split('/')
			sp0=sp0[sp0.length-1]
			let sp1 = sp0.split('.')
		    if(sp1.length>1){
		       postf=sp1[sp1.length-1]
		       let sp2=postf.split('-')
		       if(sp2.length==1){
		    	 sp2=sp1[1].split('?')
		       }
		       if(sp2.length>1){
		    	  postf=sp2[0]
		       }
		    }
			postf=postf.toLowerCase()
			//indexOf
			let type='other'
			//bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp
			let imgTypes=['bmp','jpg','jpeg','png','tif','gif','pcx','tga','exif','fpx','svg','psd','cdr','pcd','dxf','ufo','eps','ai','raw','WMF','webp']
			let videoTypes=['rm','rmvb','mp4', 'mov' ,'mtv' ,'dat' ,'wmv' ,'avi' ,'3gp' ,'amv', 'dmv' ,'flv']
			if(imgTypes.indexOf(postf)>=0){
				type='image'
			}else if(videoTypes.indexOf(postf)>=0){
				type='video'
			}
			//获取md5名称
			let newName=conf.id? conf.id:MD5(path)
			let newSp=newName.substring(0,1)
			let newPath='_doc/Cache/'+type+'/'+newSp+'/'+newName+'.'+postf
			let that=this
			if(conf.type=='local'){
				if(path.indexOf('_doc/Cache/')>=0){
					newPath=path
				}
			}
			uni.getFileInfo({
				filePath:newPath,
				success(res) {
					if (process.env.NODE_ENV === 'development') {
						console.log('from cache---'+newPath)
					}
                    callback&&callback({cache:true,msg:'from cache',type:'local',path:newPath})
					resolve({cache:true,msg:'from cache',type:'local',path:newPath})
				},
				fail(e) {
					if(conf.result=='path'){
                        callback&&callback({cache:false,msg:'本地无缓存,返回原地址',type:'local',path:path})
						resolve({cache:false,msg:'本地无缓存,返回原地址',path:path})
					}else{
						that.DownloadFile({
							path,type,newSp,postf,newName,newPath,filetype:conf.type
						}).then((rs)=>{
							if (process.env.NODE_ENV === 'development') {
								console.log(path+'---have download--'+rs)
							}
						  //#ifdef APP-PLUS
                            callback&&callback({cache:true,path:rs,msg:'文件下载成功,并异步缓存,返回下载地址',type:conf.result})
							resolve({cache:true,path:rs,msg:'文件下载成功,并异步缓存,返回下载地址',type:conf.result})
							//#endif
							//#ifndef APP-PLUS
							if(conf.result=='down'){
								//save

								if(rs.indexOf('_doc/Cache/')<0){
									let time=Math.ceil(Math.random()*1000)
									//console.log(time)
									setTimeout(function(){
										that.FileCopyTo({
											source:rs,//被复制的文件
											target :newName+'.'+postf,//复制后的路径
											dirBase:'_doc',//保存路径根目录
											dirSub:'Cache/'+type+'/'+newSp,//保存路径子目录
										})
                                        callback&&callback({cache:true,path:rs,msg:'文件下载成功,并异步缓存,返回下载地址',type:'down'})
									},time)
								} 
								resolve({cache:true,path:rs,msg:'文件下载成功,并异步缓存,返回下载地址',type:'down'})
							}else{
								that.FileCopyTo({
									source:rs,//被复制的文件
									target :newName+'.'+postf,//复制后的路径
									dirBase:'_doc',//保存路径根目录
									dirSub:'Cache/'+type+'/'+newSp,//保存路径子目录
								}).then((copyPath)=>{
                                    callback&&callback({cache:true,path:newPath,type:'cache',msg:'下载并缓存成功,返回缓存地址'})
									resolve({cache:true,path:newPath,type:'cache',msg:'下载并缓存成功,返回缓存地址'})
								}).catch((e)=>{
									console.log(e)
                                    callback&&callback({cache:false,msg:'下载成功,但是复制到缓存目录失败,返回下载地址',path:rs,type:'down'})
									resolve({cache:false,msg:'下载成功,但是复制到缓存目录失败,返回下载地址',path:rs,type:'down'})
								})
							}
								//#endif

						}).catch((e)=>{
							resolve({cache:false,msg:'文件下载失败,返回原地址',type:'source',path:path})
						})
					}
				}
			})
		})
	},
	PathToBase64:async function(path){
		return new Promise(function(resolve, reject) {
		    if (typeof window === 'object' && 'document' in window) {
		        var canvas = document.createElement('canvas')
		        var c2x = canvas.getContext('2d')
		        var img = new Image
		        img.onload = function() {
		            canvas.width = img.width
		            canvas.height = img.height
		            c2x.drawImage(img, 0, 0)
		            resolve(canvas.toDataURL())
		        }
		        img.onerror = reject
		        img.src = path
		        return
		    }
		    if (typeof plus === 'object') {
		        var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
		        bitmap.load(path, function() {
		            try {
		                var base64 = bitmap.toBase64Data()
		            } catch (error) {
		                reject(error)
		            }
		            bitmap.clear()
		            resolve(base64)
		        }, function(error) {
		            bitmap.clear()
		            reject(error)
		        })
		        return
		    }
		    if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
		        wx.getFileSystemManager().readFile({
		            filePath: path,
		            encoding: 'base64',
		            success: function(res) {
		                resolve('data:image/png;base64,' + res.data)
		            },
		            fail: function(error) {
		                reject(error)
		            }
		        })
		        return
		    }
		    reject(new Error('not support'))
		})
	},
	Base64ToPath:async function(base64){
		return new Promise(function(resolve, reject) {
		    if (typeof window === 'object' && 'document' in window) {
		        base64 = base64.split(',')
		        var type = base64[0].match(/:(.*?);/)[1]
		        var str = atob(base64[1])
		        var n = str.length
		        var array = new Uint8Array(n)
		        while (n--) {
		            array[n] = str.charCodeAt(n)
		        }
		        return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
		    }
		    var extName = base64.match(/data\:\S+\/(\S+);/)
		    if (extName) {
		        extName = extName[1]
		    } else {
		        reject(new Error('base64 error'))
		    }
		    var fileName = Date.now() + '.' + extName
		    if (typeof plus === 'object') {
		        var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
		        bitmap.loadBase64Data(base64, function() {
		            var filePath = '_doc/uniapp_temp/' + fileName
		            bitmap.save(filePath, {}, function() {
		                bitmap.clear()
		                resolve(filePath)
		            }, function(error) {
		                bitmap.clear()
		                reject(error)
		            })
		        }, function(error) {
		            bitmap.clear()
		            reject(error)
		        })
		        return
		    }
		    if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
		        var filePath = uni.env.USER_DATA_PATH + '/' + fileName
		        uni.getFileSystemManager().writeFile({
		            filePath: filePath,
		            data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
		            encoding: 'base64',
		            success: function() {
		                resolve(filePath)
		            },
		            fail: function(error) {
		                reject(error)
		            }
		        })
		        return
		    }
		    reject(new Error('not support'))
		})
	}

}
